/*
 * $Id: main.c 1087 2009-02-08 08:58:24Z jasta00 $
 *
 * Copyright (C) 2008 Josh Guilfoyle <jasta@devtcg.org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

#include "main.h"

#include "server.h"

#include "ui/gtk/main.h"

/*****************************************************************************/

static gboolean startup = FALSE;

#define GCONF_PATH_SERVER_PORT "/apps/five/server/port"

#define DEFAULT_PORT 5545

/*****************************************************************************/

void main_startup(gboolean firsttime)
{
	int port;
	gboolean reuse_db = (firsttime == TRUE) ? FALSE : TRUE;

	if (db_init(reuse_db) == FALSE)
	{
		g_error("Failed to initialize database\n");
		exit(EXIT_FAILURE);
	}

	meta_init();
	meta_crawl();

	port = gconf_client_get_int(get_gconf_client(),
	  GCONF_PATH_SERVER_PORT, NULL);

	if (port == 0)
		port = DEFAULT_PORT;

	server_init((in_port_t)port);
	server_attach();

	g_message("This machine is ready to roll, waiting for interesting events...");

	startup = TRUE;
}

static void main_shutdown(void)
{
	if (startup == FALSE)
		return;

	db_finish();
	server_finish();
	meta_finish();
}

/*
 * TODO: Eventually, I'd like to separate the core from the UI better, possibly
 * using DBus on Linux.
 */
int main(int argc, char **argv)
{
#ifdef ENABLE_NLS
	bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
#endif /* ENABLE_NLS */

	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);

	g_type_init();

	gconf_init(argc, argv, NULL);
	five_ui_init(&argc, &argv);

	/* Will call main_startup() when appropriate. */
	five_ui_main();

	main_shutdown();

	return 0;
}
